package com.smartResponse;

import java.util.ArrayList;
import java.util.Iterator;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;

import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MapViewAllLocations extends MapActivity 
{   
    private MapView mapView;
    private EventDB db = new EventDB(this);
        
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.mapviewall);

        mapView = (MapView) findViewById(R.id.mapView);
        mapView.setBuiltInZoomControls(true);
        mapView.setSatellite(false);
        mapView.setTraffic(false);
        
        Drawable marker = getResources().getDrawable(R.drawable.map_marker); 
        marker.setBounds((-marker.getIntrinsicWidth()/2),
                        -marker.getIntrinsicHeight(),
                        (marker.getIntrinsicWidth()/2), 
                        0);
        
        InterestingLocations funPlaces = new InterestingLocations(marker);
        mapView.getOverlays().add(funPlaces);
        
        GeoPoint pt = funPlaces.getCenterPt();
        int latSpan = funPlaces.getLatSpanE6();
        int lonSpan = funPlaces.getLonSpanE6();
        Log.v("Overlays", "Lat span is " + latSpan);
        Log.v("Overlays", "Lon span is " + lonSpan);

        MapController mc = mapView.getController();
        mc.setCenter(pt);
        mc.zoomToSpan((int)(latSpan*1.5), (int)(lonSpan*1.5));
    }
 
    public void viewClickHandler(View target) {
        switch(target.getId()) {
        case R.id.sat_view:
        	mapView.setSatellite(true);
        	break;
        case R.id.normal_view:
            mapView.setSatellite(false);
            mapView.setTraffic(false);
            break;
        }
        
        // This line is necessary DO NOT DELETE
        // It is a known issue with android and must be here to work properly
        mapView.postInvalidateDelayed(2000);
    }
    
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
    
    @Override
    protected boolean isLocationDisplayed() {
        return false;
    }
    
    
    class InterestingLocations extends ItemizedOverlay<OverlayItem> {
        private ArrayList<OverlayItem> locations = new ArrayList<OverlayItem>();
        private ArrayList<Double> radius = new ArrayList<Double>();
        private GeoPoint center = null;
        private float feetInMeters = (float) 3.2808399;
        private Paint innerPaint;
        private Paint borderPaint;

        public InterestingLocations(Drawable marker) {
            super(marker);
            
            db.open();
	        Cursor cursor = db.getAllLocations();
	        if(cursor.getCount() != 0) {
		        while (cursor.moveToNext()){
		            String name = cursor.getString(1);
		            float lat = Float.parseFloat(cursor.getString(4));
		            float lng = Float.parseFloat(cursor.getString(3));
	                GeoPoint temp = new GeoPoint((int)(lat*1000000),(int)(lng*1000000));
	                double thisRadius = Double.parseDouble(cursor.getString(5));
	                radius.add(thisRadius);
	                locations.add(new OverlayItem(temp,name,name));
		        }
	        }
	        db.close();
            populate();
        }
        
		public Paint getInnerPaint() {
		    if (innerPaint == null) {
		        innerPaint = new Paint();
		        innerPaint.setARGB(40, 0, 0, 175);
		        innerPaint.setAntiAlias(true);
		    }
		    return innerPaint;
		}
		public Paint getBorderPaint() {
			if (borderPaint == null) {
		        borderPaint = new Paint();
		        borderPaint.setARGB(180, 0, 0, 175);
		        borderPaint.setAntiAlias(true);
		        borderPaint.setStyle(Style.STROKE);
		        borderPaint.setStrokeWidth(1);
		    }
			return borderPaint;
		}
        
        protected void drawCircle(Canvas canvas, GeoPoint p, double radius) {
			Point screenCoords = new Point();
			int pxRadius = 0; // the radius in pixels that will be given to  the drawCircle() method
			
			// get the screen coordinates for the GeoPoint p so the circle can be drawn at that point.
			try {
				Projection proj = mapView.getProjection();
				proj.toPixels(p, screenCoords);
				pxRadius = (int)(proj.metersToEquatorPixels((float)radius/feetInMeters));
				canvas.drawCircle((screenCoords.x), (screenCoords.y), pxRadius, getInnerPaint());
				canvas.drawCircle((screenCoords.x), (screenCoords.y), pxRadius, getBorderPaint());
			} catch (Exception e) { 
				Log.d("Map",e.toString());
			}
        }

        //  We added this method to find the middle point of the cluster
        //  Start each edge on its opposite side and move across with each point.
        //  The top of the world is +90, the bottom -90,
        //  the west edge is -180, the east +180
        public GeoPoint getCenterPt() {
            if(center == null) {
                int northEdge = -90000000;   // i.e., -90E6 microdegrees
                int southEdge = 90000000;
                int eastEdge = -180000000;
                int westEdge = 180000000;
                Iterator<OverlayItem> iter = locations.iterator();
                while(iter.hasNext()) {
                    GeoPoint pt = iter.next().getPoint();
                    if(pt.getLatitudeE6() > northEdge) northEdge = pt.getLatitudeE6();
                    if(pt.getLatitudeE6() < southEdge) southEdge = pt.getLatitudeE6();
                    if(pt.getLongitudeE6() > eastEdge) eastEdge = pt.getLongitudeE6();
                    if(pt.getLongitudeE6() < westEdge) westEdge = pt.getLongitudeE6();
                }
                center = new GeoPoint(((northEdge + southEdge)/2),
                        ((westEdge + eastEdge)/2));
            }
            return center;
        }

        @Override
        public void draw(Canvas canvas, MapView mapview, boolean shadow) {
                // Here is where we can eliminate shadows by setting to false
                super.draw(canvas, mapview, shadow);
                
                // Drawing circles around the map markers
            	for(int i = 0; i < locations.size(); i++)
            		drawCircle(canvas,locations.get(i).getPoint(),radius.get(i));
                	
        }

        @Override
        protected OverlayItem createItem(int i) {
            return locations.get(i);
        }

        @Override
        public int size() {
            return locations.size();
        }
    }
	// Menu Layout
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
        menu.add(0,1,0,"Home").setIcon(R.drawable.home);
	    return true;
	}
    @Override
     public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case 1:
			  Intent home_intent_menu = new Intent(MapViewAllLocations.this, MainActivity.class);
			  startActivity(home_intent_menu);
			  
			  return true;
          }
		return false;
    }
}